<template>
  <div class="work_stage_edit">
    <process-template
      ref="processTemplate"
      @success="handleTempSuccess"
    ></process-template>
    <div class="stage_container" :style="bg">
      <slot></slot>
      <draggable
        element="div"
        v-model="stageList"
        class="drag_content"
        @update="handleDrag"
        :options="dragOptions">
        <transition-group class="cards_box" type="transition" :name="'flip-list'">
          <div
            class="drag_chrome_fix"
            :key="`${index}`"
            v-for="(item, index) in stageList">
            <div class="card_process">
              <div class="card_number">{{index + startIndex}}</div>
              <div class="card_top">
                <p class="card_text">工序编号：{{item.workstageNumber}}</p>
                <p class="card_text">工序名称：{{item.workstageName}}</p>
                <p class="card_text">检验类型：{{item.inspectionTypeLabel}}</p>
                <p class="card_text">跨工序开工：{{item.allowSkipToStartLabel}}</p>
                <p class="card_text">
                  <span style="vertical-align: middle">定额工时：</span>
                  <tooltip-txt style="display: inline-block;vertical-align: middle" :text="item.estimateEffort + '小时'"></tooltip-txt>
                </p>
              </div>
              <div class="card_bottom">
                <p class="card_text">派工规则：{{item.assignRule}}</p>
                <p class="card_text">工序简述：{{item.summary}}</p>
                <div class="desc">
                  <p class="desc_label">工序描述：</p>
                  <p><span class="desc_text">{{item.remarks}}</span></p>
                </div>
              </div>
              <div class="card_operate">
                <div class="operate_box">
                  <div v-if="!item.paramTemplateId" class="record_temp" @click="openProcessTemplate(item, true)">
                    <i class="iconfont icon-gongxujilumoban"></i>
                    <div>模板</div>
                    <div>新增</div>
                  </div>
                  <div v-else class="record_temp" @click="openProcessTemplate(item, false)">
                    <i class="iconfont icon-gongxujilumoban"></i>
                    <div>模板</div>
                    <div>详情</div>
                  </div>
                  <div @click="openDialogEdit(item, index)">
                    <i class="iconfont icon-btn_edit"></i>
                    修改
                  </div>
                  <div @click="handleDelete(index)">
                    <i class="iconfont icon-btn_delete"></i>
                    删除
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="drag_chrome_fix" key="e">
            <div class="card_process card_process_add" @click="openDialogAdd">
              <div class="card_add_icon">
                <i class="iconfont icon-btn_addnew"></i>
              </div>
              <p class="add_text">新增工序</p>
            </div>
          </div>
          <div class="drag_chrome_fix" key="a">
            <div class="card_process" style="height: 0;visibility: hidden;margin-bottom: 0"></div>
          </div>
          <div class="drag_chrome_fix" key="b">
            <div class="card_process" style="height: 0;visibility: hidden;margin-bottom: 0"></div>
          </div>
          <div class="drag_chrome_fix" key="c">
            <div class="card_process" style="height: 0;visibility: hidden;margin-bottom: 0"></div>
          </div>
          <div class="drag_chrome_fix" key="d">
            <div class="card_process" style="height: 0;visibility: hidden;margin-bottom: 0"></div>
          </div>
        </transition-group>
      </draggable>
    </div>
    <stage-dialog
      ref="dialog"
      :workstageData="workstageData"
      @add="handleAdd"
      @update="handleUpdate"
    ></stage-dialog>
  </div>
</template>

<script>
import bgGongyi from '@/assets/img/bg_gongyi.png'
import draggable from 'vuedraggable'
// 编辑工序弹框
import StageDialog from './StageDialog'
import {objectCombine} from '../../utils'
import {ProcessTemplate} from '../Template'

export default {
  name: 'WorkStageEdit',
  components: {
    draggable,
    StageDialog,
    ProcessTemplate
  },
  props: {
    // 可选工序
    workstageData: {
      type: Array,
      default() {
        return []
      }
    },
    // 拖拽标题开始的索引
    startIndex: {
      type: Number,
      default: 1
    },
    // 物料名称
    materialName: {
      type: String,
      required: true
    },
    // 批次类型
    entry: {
      type: String,
      required: true
    },
  },
  data() {
    return {
      bg: {
        backgroundImage: 'url(' + bgGongyi + ')'
      },
      stageList: [],
      // 是否有工艺修改
      hasStageChange: false
    }
  },
  computed: {
    dragOptions() {
      return {
        animation: 0,
        group: 'description',
        ghostClass: 'ghost',
      }
    },
  },
  methods: {
    openProcessTemplate(item, isNew) {
      let obj = {
        // 物料名称
        materialName: this.materialName,
        // 工序Id
        workstageId: item.id,
        // 工序编号
        workstageNumber: item.workstageNumber,
        // 工序名称
        workstageName: item.workstageName,
        // 批次类型
        entry: this.entry,
        // 是否新增
        isNew
      }
      if (this.hasStageChange) {
        this.confirmOpen('有未保存的工序，需要先保存工序', '确认保存')
          .then(() => {
            this.$emit('saveStage')
          })
      } else {
        this.$refs.processTemplate.openDialog(obj)
      }
    },
    initStageList(stageList) {
      this.stageList = stageList
    },
    // 编辑工序弹框
    openDialogEdit(item, index) {
      this.$refs.dialog.openDialog(item, index)
    },
    // 添加工序弹框
    openDialogAdd() {
      this.$refs.dialog.openDialog()
    },
    handleDrag() {
      this.hasStageChange = true
      this.$emit('change', this.stageList)
    },
    handleAdd(item) {
      this.stageList.push(this.buildWorkStageItem(item))
      this.hasStageChange = true
      this.$emit('change', this.stageList)
    },
    handleUpdate(item, index) {
      let oldWorkStageItem = this.stageList[index]
      let newWorkStageItem = this.buildWorkStageItem(item)
      // 如果更换了工序，则清除该条目的id
      if (newWorkStageItem.workstageId !== oldWorkStageItem.workstageId) {
        delete oldWorkStageItem.id
      }
      objectCombine(oldWorkStageItem, newWorkStageItem)
      this.hasStageChange = true
      this.$emit('change', this.stageList)
    },
    handleDelete(index) {
      this.confirmDelete().then(() => {
        this.stageList.splice(index, 1)
        this.hasStageChange = true
        this.$emit('change', this.stageList)
        this.$message.success({
          message: '删除成功!',
          duration: 1500,
          center: true
        })
      })
    },
    /**
     * 构建工序项
     * @param item {object} v-model的项
     * @returns {object} 展示的项，包括需要传值的ID
     */
    buildWorkStageItem(item) {
      return {
        workstageId: item.selectedWorkstageID, // 选择的工序ID
        workstageNumber: this.getWorkStage(item.selectedWorkstageID).number, // 选择的工序编号
        workstageName: this.getWorkStage(item.selectedWorkstageID).name, // 选择的工序名称
        inspectionTypeId: item.inspectionTypeId, // 检验类型ID
        inspectionTypeLabel: this.getInspectionTypeLabel(item.inspectionTypeId), // 检验类型值
        allowSkipToStartId: item.allowSkipToStartId, // 跨工序开工ID
        allowSkipToStartLabel: this.getAllowSkipToStartLabel(item.allowSkipToStartId), // 跨工序开工值
        estimateEffort: item.estimateEffort, // 估计工时
        assignRule: this.assignRuleToStr(item.assignRule), // 派工规则
        summary: item.summary, // 工序简述
        remarks: item.remarks, // 工序备注
      }
    },
    /**
     * 根据工艺ID获取工序编号、工序名称
     * @param workstageID 工序ID
     * @returns {*}
     */
    getWorkStage(workstageID) {
      return this.workstageData.find(value => value.id === workstageID) || {number: '', name: ''}
    },
    /**
     * 根据检验类型id获取检验类型名称
     * @param id
     * @returns {*}
     */
    getInspectionTypeLabel(id) {
      let temp = this.$store.state.dict.inspectionType.labels.find(dict => dict.id === id) || {label: ''}
      return temp.label
    },
    /**
     * 根据跨工序开工id获取跨工序开工名称
     * @param id
     * @returns {*}
     */
    getAllowSkipToStartLabel(id) {
      let temp = this.$store.state.dict.booleanType.labels.find(dict => dict.id === id) || {label: ''}
      return temp.label
    },
    // 保存时获取派工规则字符串
    assignRuleToStr(num) {
      if (num === 0) {
        return 'T'
      } else {
        return 'T-' + num
      }
    },
    handleTempSuccess() {
      this.$emit('tempSave')
    }
  },
}
</script>

<style lang="less" scoped>
  @import './workStageEdit';
</style>
